<template>
  <aside class="w-full lg:w-80 xl:w-96 shrink-0 h-fit lg:h-full">
    <div class="bg-white rounded-2xl shadow-sm ring-1 ring-gray-200 p-6 h-full overflow-y-auto">
      <div class="flex items-center gap-4">
        <img 
          :src="avatar" 
          class="w-20 h-20 rounded-2xl object-cover cursor-pointer hover:ring-2 hover:ring-[#635BFF] hover:ring-opacity-50 transition-all duration-200 draggable-avatar" 
          @click="showAvatarPreview"
          draggable="true"
          @dragstart="handleDragStart"
          @dragend="handleDragEnd"
        />
        <div>
          <div class="text-2xl font-semibold text-gray-900">{{ name }}</div>
          <div class="mt-2 flex flex-wrap gap-2">
            <span v-for="t in tags" :key="t" class="h-7 px-2 rounded-md bg-indigo-50 text-indigo-600 text-xs inline-flex items-center">{{ t }}</span>
          </div>
        </div>
      </div>

      <div class="mt-4 flex items-center gap-3">
        <button
          class="flex-1 h-10 rounded-xl bg-[#635BFF] text-white text-sm hover:bg-[#5a4fcf]"
          @click="toggleFavorite"
        >
          {{ isFavorited ? '取消收藏' : '收藏角色' }}
        </button>
        <button
          class="h-10 w-10 rounded-xl ring-1 ring-gray-200 hover:bg-gray-50"
          :class="isFavorited ? 'text-amber-500' : 'text-gray-500'"
          @click="toggleFavorite"
          :title="isFavorited ? '取消收藏' : '收藏'"
        >
          <svg v-if="isFavorited" xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mx-auto" viewBox="0 0 24 24" fill="currentColor"><path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 6 4 4 6.5 4c1.74 0 3.41 1 4.22 2.44C11.09 5 12.76 4 14.5 4 17 4 19 6 19 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/></svg>
          <svg v-else xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mx-auto" viewBox="0 0 24 24" fill="currentColor"><path d="M12.1 8.64l-.1.1-.11-.11C10.14 6.6 7.1 6.6 5.15 8.56c-1.95 1.95-1.95 5.12 0 7.07L12 22.5l6.85-6.87c1.95-1.95 1.95-5.12 0-7.07-1.96-1.95-4.99-1.95-6.95 0z"/></svg>
        </button>
        <button
          class="h-10 w-10 rounded-xl ring-1 ring-gray-200 text-gray-500 hover:bg-gray-50"
          @click="handlePlay"
          title="播放招呼语"
        >
          <svg class="h-5 w-5 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 4.663 12 5.109 12 6v12c0 .891-1.077 1.337-1.707.707L5.586 15z" />
          </svg>
        </button>
      </div>

      <div class="mt-6">
        <div class="text-lg font-semibold text-gray-900">角色设定</div>
        <p class="mt-2 text-sm text-gray-600 leading-6">
          {{ intro || '这位角色还没有简介~' }}
        </p>
      </div>
    </div>
    
    <!-- 头像预览模态框 -->
    <div 
      v-if="showPreview" 
      class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50"
      @click="hideAvatarPreview"
    >
      <div class="relative max-w-4xl max-h-[90vh] p-4">
        <!-- 关闭按钮 -->
        <button 
          @click="hideAvatarPreview"
          class="absolute -top-2 -right-2 z-10 w-8 h-8 bg-white rounded-full shadow-lg flex items-center justify-center hover:bg-gray-100 transition-colors"
        >
          <svg class="w-4 h-4 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
          </svg>
        </button>
        
        <!-- 放大的头像 -->
        <div class="bg-white rounded-2xl shadow-2xl overflow-hidden avatar-preview">
          <img 
            :src="avatar" 
            alt="角色头像预览" 
            class="max-w-full max-h-[80vh] object-contain"
          />
        </div>
      </div>
    </div>
  </aside>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { characterInfo } from '@/api'

const props = defineProps<{
  name: string
  avatar?: string
  tags: string[]
  intro?: string
  // 新增：收藏状态与角色ID
  isFavorited?: number | boolean
  id?: number | string
}>()

// 头像预览状态
const showPreview = ref(false)

// 拖拽状态
const isDragging = ref(false)

// 事件发射
const emit = defineEmits<{
  (e: 'setBackground', imageUrl: string): void
  (e: 'removeBackground'): void
}>()

// 将父级传入的 isFavorited(0/1 或 boolean) 同步到本地状态
const localFavorited = ref(!!props.isFavorited)
watch(() => props.isFavorited, (v) => { localFavorited.value = !!v })

const isFavorited = computed(() => localFavorited.value)

const toggleFavorite = async () => {
  if (!props.id && props.id !== 0) return
  try {
    if (localFavorited.value) {
      const res = await characterInfo.unfavorite(props.id as any)
      if (res?.code === 0) localFavorited.value = false
    } else {
      const res = await characterInfo.favorite(props.id as any)
      if (res?.code === 0) localFavorited.value = true
    }
  } catch (e) {
    console.error('[RoleSidebar] 切换收藏失败:', e)
  }
}

// 显示头像预览
const showAvatarPreview = () => {
  if (props.avatar) {
    showPreview.value = true
  }
}

// 隐藏头像预览
const hideAvatarPreview = () => {
  showPreview.value = false
}

// 拖拽开始
const handleDragStart = (event: DragEvent) => {
  if (event.dataTransfer && props.avatar) {
    isDragging.value = true
    event.dataTransfer.setData('text/plain', props.avatar)
    event.dataTransfer.setData('application/json', JSON.stringify({
      type: 'avatar',
      imageUrl: props.avatar
    }))
    event.dataTransfer.effectAllowed = 'copy'
    
    // 设置拖拽时的视觉反馈
    if (event.target instanceof HTMLElement) {
      event.target.style.opacity = '0.5'
    }
  }
}

// 拖拽结束
const handleDragEnd = (event: DragEvent) => {
  isDragging.value = false
  if (event.target instanceof HTMLElement) {
    event.target.style.opacity = '1'
  }
}

// 键盘事件处理
const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Escape' && showPreview.value) {
    hideAvatarPreview()
  }
}

// 监听键盘事件
onMounted(() => {
  document.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})

import { voicePlayerManager } from '@/utils/voicePlayerManager'

// 防抖标志
let isPlaying = false

// 播放招呼语功能（使用全局播放器管理器）
const handlePlay = async () => {
  if (!props.id && props.id !== 0) return
  
  // 防止重复点击
  if (isPlaying) {
    return
  }
  
  try {
    isPlaying = true
    
    // 获取新的流式播放接口URL
    const streamUrl = characterInfo.voiceStreamPlay(props.id as any)
    
    // 使用全局播放器管理器
    await voicePlayerManager.play(streamUrl, {
      sampleRate: 22050,
      timeout: 30000,
      onStart: () => {
        
      },
      onEnd: () => {
        isPlaying = false
      },
      onError: (error) => {
        isPlaying = false
      }
    })
    
  } catch (e) {
    // 播放失败不阻断页面
    
    isPlaying = false
  }
}
</script>

<style scoped>
/* 头像预览图片样式 */
.avatar-preview img {
  transition: transform 0.3s ease;
}

.avatar-preview img:hover {
  transform: scale(1.02);
}

/* 拖拽样式 */
.draggable-avatar {
  transition: opacity 0.2s ease, transform 0.2s ease;
}

.draggable-avatar:hover {
  transform: scale(1.05);
}

.draggable-avatar:active {
  transform: scale(0.95);
}
</style>


